package com.chj.comp.common.auth.security.granter;

import com.chj.comp.common.auth.entity.SysUser;
import com.chj.comp.common.auth.security.service.SecurityUserDetailService;
import com.chj.comp.common.auth.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author ：cuihui
 * @date ：Created in 2023/2/14
 * @description：自定义短信验证码授权类型
 * @modified By：
 */
public class SmsCodeTokenGranter extends AbstractTokenGranter {

    private static final String SMS_GRANT_TYPE = "sms_code";

    private SecurityUserDetailService securityUserDetailService;

    private ISysUserService sysUserService;

    public SmsCodeTokenGranter(AuthorizationServerTokenServices tokenServices,
                               ClientDetailsService clientDetailsService,
                               OAuth2RequestFactory requestFactory,
                               SecurityUserDetailService securityUserDetailService,
                               ISysUserService sysUserService) {
        super(tokenServices, clientDetailsService, requestFactory, SMS_GRANT_TYPE);
        this.securityUserDetailService = securityUserDetailService;
        this.sysUserService = sysUserService;
    }


    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client,
                                                           TokenRequest tokenRequest) {

        Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());

        System.out.println(parameters.toString());
        // 客户端提交的手机号码
        String phoneNumber = parameters.get("phone");
        if (StringUtils.isBlank(phoneNumber)) {
            throw new AccessDeniedException("电话号码不能为空");
        }
        // 校验验证码（接入redis缓存校验，此处省略）
        String code = parameters.get("code");

        if (!code.equals("888888")) {
            throw new AccessDeniedException("验证码错误或已失效");
        }

        SysUser sysUser = sysUserService.getUserByPhone(phoneNumber);
        UserDetails user = securityUserDetailService.loadUserByUsername(sysUser.getUsername());

        AbstractAuthenticationToken userAuth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());

        userAuth.setDetails(parameters);
        OAuth2Request oAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(oAuth2Request, userAuth);
    }
}
